package com.ruoyi.develop.finance.financeInvoiceReceipt.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;

import javax.annotation.Resource;

import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.finance.financeAr.service.IFinanceArService;
import com.ruoyi.develop.goodsCustomer.domain.GoodsCustomer;
import com.ruoyi.develop.goodsCustomer.service.IGoodsCustomerService;
import com.ruoyi.develop.goodsInvoice.domain.GoodsInvoice;
import com.ruoyi.develop.goodsInvoice.mapper.GoodsInvoiceMapper;
import com.ruoyi.develop.goodsInvoice.service.IGoodsInvoiceService;
import com.ruoyi.develop.goodsInvoiceDetail.domain.GoodsInvoiceDetail;
import com.ruoyi.develop.goodsInvoiceDetail.mapper.GoodsInvoiceDetailMapper;
import com.ruoyi.develop.goodsInvoiceDetail.service.IGoodsInvoiceDetailService;
import com.ruoyi.develop.project.domain.Project;
import com.ruoyi.develop.projectBaseInfo.domain.ProjectBaseInfo;
import com.ruoyi.develop.projectBaseInfo.service.IProjectBaseInfoService;
import org.apache.poi.ss.usermodel.DateUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.develop.finance.financeInvoiceReceipt.mapper.FinanceInvoiceReceiptMapper;
import com.ruoyi.develop.finance.financeInvoiceReceipt.domain.FinanceInvoiceReceipt;
import com.ruoyi.develop.finance.financeInvoiceReceipt.service.IFinanceInvoiceReceiptService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

/**
 * 客户回款单Service业务层处理
 *
 * @author lmm
 * @date 2025-08-09
 */
@Service
public class FinanceInvoiceReceiptServiceImpl implements IFinanceInvoiceReceiptService {
    @Resource
    private FinanceInvoiceReceiptMapper financeInvoiceReceiptMapper;
    @Resource
    private IGoodsCustomerService goodsCustomerService;
    @Resource
    private IProjectBaseInfoService projectBaseInfoService;
    @Resource
    private IGoodsInvoiceService goodsInvoiceService;

    @Resource
    private GoodsInvoiceMapper goodsInvoiceMapper;

    @Resource
    private IGoodsInvoiceDetailService goodsInvoiceDetailService;
    @Resource
    private GoodsInvoiceDetailMapper goodsInvoiceDetailMapper;

    @Resource
    private IFinanceArService financeArService;


    @Value(value = "${ruoyi.path}")
    public String basePath;
    @Value(value = "${ruoyi.templatePath}")
    public String templatePath;
    @Value(value = "${ruoyi.templateImport}")
    public String templateImport;

    /**
     * 查询客户回款单
     *
     * @param id 客户回款单主键
     * @return 客户回款单
     */
    @Override
    public FinanceInvoiceReceipt selectById(String id) {
        return financeInvoiceReceiptMapper.selectById(id);
    }

    /**
     * 查询客户回款单列表
     *
     * @param entity 客户回款单
     * @return 客户回款单
     */
    @Override
    public List<FinanceInvoiceReceipt> selectList(FinanceInvoiceReceipt entity) {
        return financeInvoiceReceiptMapper.selectList(entity);
    }

    /**
     * 新增客户回款单
     *
     * @param entity 客户回款单
     * @return 结果
     */
    @Override
    public int insert(FinanceInvoiceReceipt entity) {
        if (StringUtils.isBlank(entity.getId())) {
            entity.setId(IdUtils.fastSimpleUUID());
        }
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        return financeInvoiceReceiptMapper.insert(entity);
    }

    /**
     * 修改客户回款单
     *
     * @param entity 客户回款单
     * @return 结果
     */
    @Override
    public int update(FinanceInvoiceReceipt entity) {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return financeInvoiceReceiptMapper.update(entity);
    }

    /**
     * 批量删除客户回款单
     *
     * @param ids 需要删除的客户回款单主键
     * @return 结果
     */
    @Override
    public int deleteByIds(String[] ids) {
        return financeInvoiceReceiptMapper.deleteByIds(ids);
    }

    /**
     * 删除客户回款单信息
     *
     * @param id 客户回款单主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return financeInvoiceReceiptMapper.deleteById(id);
    }

    @Override
    @Transactional
    public Map<String, Object> importData(FinanceInvoiceReceipt entity, MultipartFile file) {
        String tmplName = "financeInvoiceReceipt.xml";
        String errortext = "";
        Map<String, Object> map = new HashMap<>();
        List<FinanceInvoiceReceipt> listAdd = new ArrayList<>();
        int insertCount = 0;
        try {
            InputStream in = new FileInputStream(basePath + File.separator
                    + templatePath + File.separator + templateImport + File.separator + tmplName);
            XLSReader mainReader = ReaderBuilder.buildFromXML(in);
            List<FinanceInvoiceReceipt> list = new ArrayList<>();
            Map beans = new HashMap();
            beans.put("list", list);
            XLSReadStatus readStatus = mainReader.read(file.getInputStream(), beans);
            if (readStatus.isStatusOK()) {
                for (FinanceInvoiceReceipt info : list) {

                    String money = info.getParams().get("money") != null ? info.getParams().get("money").toString() : "";
                    if (StringUtils.isBlank(money)) {
                        errortext += "订单号：" + info.getOrderCode() + "，数据，回款金额不能为空！";
                    } else {
                        info.setMoney(new BigDecimal(money));
                    }

//                    if (StringUtils.isBlank(info.getCustomerName())) {
//                        errortext += "客户不能为空，请填写后导入！";
//                    } else {
//                        GoodsCustomer goodsCustomer = goodsCustomerService.selectByName(info.getCustomerName());
//                        if (goodsCustomer != null) {
//                            info.setCustomerId(goodsCustomer.getId());
//                            info.setCustomerName(goodsCustomer.getName());
//                        } else {
//                            errortext += info.getCustomerName() + "客户不存在，请检查后导入！";
//                        }
//                    }

                    if (StringUtils.isBlank(info.getOrderCode())) {
                        errortext += "订单号不能为空，请填写后导入！";
                    } else {
//                        ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectByCode(info.getOrderCode());
//                        if (projectBaseInfo != null) {
//                            info.setOrderId(projectBaseInfo.getId());
//                            info.setOrderCode(projectBaseInfo.getCode());
//                        } else {
//                            errortext += info.getOrderCode() + "订单号不存在，请检查后导入！";
//                        }
                    }


                    FinanceInvoiceReceipt params = new FinanceInvoiceReceipt();
                    params.setCustomerName(info.getCustomerName());
                    params.setMoney(info.getMoney());
                    params.setOrderCode(info.getOrderCode());
                    List<FinanceInvoiceReceipt> receiptList = financeInvoiceReceiptMapper.selectList(params);
                    if (receiptList.size() > 0) {
                        errortext += "订单号：" + info.getOrderCode() + "，客户回款单已存在，请检查后导入！";
                    } else {
                        listAdd.add(info);
                    }

                }
            }

            if (StringUtils.isBlank(errortext)) {
                for (FinanceInvoiceReceipt receipt : listAdd) {
                    insertCount += this.insert(receipt);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("errorText", errortext);
        map.put("num", insertCount);
        return map;
    }

    @Override
    public void autoWriteOff(FinanceInvoiceReceipt receipt) {

        // 查询待核销发票
        GoodsInvoice params = new GoodsInvoice();
        params.setCustomerId(receipt.getCustomerId());
        params.setProjectId(receipt.getOrderId());
        params.setAmount(receipt.getMoney());
        params.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
        GoodsInvoice invoice = goodsInvoiceService.selectByInvoice(params);
        if (invoice == null) {
            receipt.setStatus(BusinessConstants.INVOICE_RECEIPT_STATUS_FAILED);
            receipt.setWay(BusinessConstants.INVOICE_RECEIPT_WAY_AUTO);
            financeInvoiceReceiptMapper.update(receipt);
        }
        if (invoice != null) {
            receipt.setInvoiceId(invoice.getId());
            receipt.setStatus(BusinessConstants.INVOICE_RECEIPT_STATUS_SUCCESS);
            receipt.setWay(BusinessConstants.INVOICE_RECEIPT_WAY_AUTO);
            financeInvoiceReceiptMapper.update(receipt);
            // 插入核销记录
            GoodsInvoice goodsInvoice = goodsInvoiceService.selectById(invoice.getId());
            goodsInvoice.setPinMoney(goodsInvoice.getPinMoney().add(receipt.getMoney()));
            goodsInvoice.setPinRemain(goodsInvoice.getPinRemain().subtract(receipt.getMoney()));
            // 判断是否核销完成
            if (goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) == 0) {
                goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
            }
            if (goodsInvoice.getPinMoney().compareTo(goodsInvoice.getAmount()) < 0) {
                goodsInvoice.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
            }
            goodsInvoiceMapper.update(goodsInvoice);
            GoodsInvoiceDetail invoiceDetail = new GoodsInvoiceDetail();
            invoiceDetail.setInvoiceId(receipt.getInvoiceId());
            invoiceDetail.setCustomerId(goodsInvoice.getCustomerId());
            invoiceDetail.setPinDate(new Date());
            invoiceDetail.setPinMoney(receipt.getMoney());
            invoiceDetail.setCustomerName(goodsInvoice.getCustomerName());
            invoiceDetail.setProjectNo(goodsInvoice.getProjectNo());
            invoiceDetail.setProjectId(goodsInvoice.getProjectId());
            goodsInvoiceDetailService.insertNoUser(invoiceDetail);
            // 核销之后 生成应收 回款
            financeArService.addByBackMoney(invoiceDetail);
            ProjectBaseInfo projectBaseInfo = projectBaseInfoService.selectById(goodsInvoice.getProjectId());
            if (projectBaseInfo != null) {
                projectBaseInfo.setBackMoney(projectBaseInfo.getBackMoney().add(goodsInvoice.getPinMoney()));
                projectBaseInfo.setRemainMoney(projectBaseInfo.getRemainMoney().subtract(goodsInvoice.getPinMoney()));
                if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) == 0) {
                    projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_YHX);
                    projectBaseInfo.setEndDate(new Date());
                }

                if (projectBaseInfo.getRemainMoney().compareTo(BigDecimal.ZERO) > 0) {
                    projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_BFHX);
                }
                if (projectBaseInfo.getRemainMoney().compareTo(projectBaseInfo.getContractMoney()) == 0) {
                    projectBaseInfo.setFundCallback(BusinessConstants.INVOICE_BACK_STATUS_WHX);
                }
                projectBaseInfoService.updateBackMoney(projectBaseInfo);
            }
        }

    }

}
